package com.menker.app.util;


import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.menker.app.R;
import com.menker.app.biz.WechatShareManager;
import com.menker.app.common.Utils;
import com.menker.app.rest.CustomTrust;
import com.menker.app.rest.UnSafeHostnameVerifier;
import com.menker.app.rest.result.ProductShareInfo;
import com.menker.app.ui.generalweb.GeneralWebViewActivity;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.onekeyshare.themes.classic.ClassicTheme;
import cn.sharesdk.onekeyshare.themes.classic.PlatformPage;
import cn.sharesdk.onekeyshare.themes.classic.port.PlatformPagePort;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static cn.sharesdk.framework.Platform.SHARE_IMAGE;

public class ShareUtils {
    /**
     * 显示分享面板
     * @param activity 上下文
     * @param title 标题
     * @param content 内容
     * @param shareUrl 分享地址
     * @param iconUrl 分享icon
     */
    public static void showSharePanel(final Activity activity, final WechatShareManager wechatShareManager, final String title, final String content,
                                      String shareUrl, String iconUrl) {

        if (activity == null) {
            return;
        }

//        if (!TextUtils.isEmpty(shareUrl) && shareUrl.startsWith("https")) {
//            shareUrl = shareUrl.replace("https://", "http://");
//        }

        if (!TextUtils.isEmpty(iconUrl) && iconUrl.startsWith("https")) {
            iconUrl = iconUrl.replace("https://", "http://");
        }

        final String httpShareUrl = shareUrl;
        final String httpIconUrl = iconUrl;

            new Thread(new Runnable() {
            @Override
            public void run() {
                final boolean isImgUrlWork = checkURL(activity, httpIconUrl);

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        OnekeyShare oks = new OnekeyShare();
                        // 关闭sso授权
                        oks.disableSSOWhenAuthorize();

                        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
                        oks.setTitle(title);
                        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                        oks.setTitleUrl(httpShareUrl);
                        // text是分享文本，所有平台都需要这个字段
                        oks.setText(content);
                        if(isImgUrlWork) {
                            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                            oks.setImageUrl(httpIconUrl);
                        } else {
                            // TODO: 没有image时候无法正常显示
//                            oks.setImagePath();
                        }

                        // url仅在微信（包括好友和朋友圈）中使用
                        oks.setUrl(httpShareUrl);
                        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                        oks.setComment(content);
                        // site是分享此内容的网站名称，仅在QQ空间使用
                        oks.setSite(activity.getString(R.string.app_name));
                        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                        oks.setSiteUrl(httpShareUrl);
                        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
                            @Override
                            public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
//                                if(SinaWeibo.NAME.equals(platform.getName())){
//                                    String text = content.concat(shareUrl);
//                                    paramsToShare.setText(text);
//                                }
                            }
                        });
                        // 添加回调事件
                        oks.setCallback(new PlatformActionListener() {
                            @Override
                            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                                activity.runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        Toast.makeText(activity, "分享成功", Toast.LENGTH_SHORT).show();
//                                    }
//                                });
                            }

                            @Override
                            public void onError(Platform platform, int i, Throwable throwable) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "分享失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onCancel(Platform platform, int i) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "取消分享", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });

                        // 自定义朋友圈分享
//                        Bitmap logo = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ssdk_oks_classic_wechatmoments);
//                        String label = "微信朋友圈";
//                        oks.setCustomerLogo(logo, label, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                // 分享链接
//                                new Thread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        WechatShareManager.ShareContentWebPage shareContentWebPage = (WechatShareManager.ShareContentWebPage) wechatShareManager.getShareContentWebPage(title, title, shareUrl, iconUrl);
//                                        wechatShareManager.shareByWebchat(shareContentWebPage, WechatShareManager.WECHAT_SHARE_TYPE_TIMELINE);
//                                    }
//                                }).start();
//                            }
//                        });
                        // 启动分享GUI
                        oks.show(activity);
                    }
                });
            }
        }).start();
    }

    public static void showSharePanel(final Activity activity, final ProductShareInfo shareInfo) {
        if (activity == null) {
            return;
        }

        String iconUrl = shareInfo.imgUrl;
        if (!TextUtils.isEmpty(iconUrl)) {
            if (iconUrl.startsWith("https")){
                iconUrl = iconUrl.replace("https://", "http://");
            }else if (iconUrl.startsWith("http")){

            }else {
                iconUrl = "http:".concat(iconUrl);
            }
        }


        final String httpShareUrl = shareInfo.shareUrl;
        final String httpIconUrl = iconUrl;

        new Thread(new Runnable() {
            @Override
            public void run() {
                final boolean isImgUrlWork = checkURL(activity, httpIconUrl);

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        OnekeyShare oks = new OnekeyShare();
                        // 关闭sso授权
                        oks.disableSSOWhenAuthorize();

                        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
                        oks.setTitle(shareInfo.title);
                        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                        oks.setTitleUrl(httpShareUrl);
                        // text是分享文本，所有平台都需要这个字段
                        oks.setText(shareInfo.content);
                        if(isImgUrlWork) {
                            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                            oks.setImageUrl(httpIconUrl);
                        } else {
                            // TODO: 没有image时候无法正常显示
                        }


                        // url仅在微信（包括好友和朋友圈）中使用
                        oks.setUrl(httpShareUrl);
                        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//                        oks.setComment(shareInfo.itemUrl);
                        // site是分享此内容的网站名称，仅在QQ空间使用
                        oks.setSite(activity.getString(R.string.app_name));
                        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                        oks.setSiteUrl(httpShareUrl);
                        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
                            @Override
                            public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
                            }
                        });
                        // 添加回调事件
                        oks.setCallback(new PlatformActionListener() {
                            @Override
                            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                                activity.runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        Toast.makeText(activity, "分享成功", Toast.LENGTH_SHORT).show();
//                                    }
//                                });
                            }

                            @Override
                            public void onError(Platform platform, int i, Throwable throwable) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "分享失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onCancel(Platform platform, int i) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "取消分享", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                        // 启动分享GUI
                        oks.show(activity);
                    }
                });
            }
        }).start();

    }

    public static void sharePic(final Activity activity, final String imgUrl, final GeneralWebViewActivity.OnSharePicListener listener) {
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setShareType(Platform.SHARE_IMAGE);

        oks.setImageUrl(imgUrl);

        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(final Platform platform, int i, HashMap<String, Object> hashMap) {
                listener.onShareFinished(true, platform);
            }

            @Override
            public void onError(final Platform platform, int i, Throwable throwable) {
                listener.onShareFinished(false, platform);
            }

            @Override
            public void onCancel(final Platform platform, int i) {
                listener.onShareFinished(false, platform);
            }
        });
        // 启动分享GUI
        oks.show(activity);
    }

    private static boolean checkURL(Activity activity, String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }

        CustomTrust customTrust = new CustomTrust(activity);

        try {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            httpClientBuilder
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS);

            if (!TextUtils.isEmpty(url) && url.startsWith("https")) {
                // 添加https
                httpClientBuilder
                        .sslSocketFactory(customTrust.sslSocketFactory, customTrust.trustManager)
                        .hostnameVerifier(new UnSafeHostnameVerifier());
            }

            OkHttpClient httpClient = httpClientBuilder.build();
            Request request = new Request.Builder().url(url).build();
            Response response = httpClient.newCall(request).execute();

            return response.isSuccessful();

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
